import React, { useState, useEffect } from 'react';
import Head from 'next/head';
import { useAuth } from '../contexts/AuthContext';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import AuthModal from '@/components/AuthModal';
import axios from 'axios';

interface Message {
  id: number;
  email: string;
  content: string;
  created_at: string;
}

interface MessagesResponse {
  messages: Message[];
  total: number;
  pages: number;
  current_page: number;
}

const FeedbackPage: React.FC = () => {
  const [feedback, setFeedback] = useState('');
  const [showLoginRegister, setShowLoginRegister] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const { user, token } = useAuth();

  const fetchMessages = async (page: number) => {
    try {
      const response = await axios.get<MessagesResponse>(`/auth/messages?page=${page}&per_page=6`);
      setMessages(response.data.messages);
      setTotalPages(response.data.pages);
      setCurrentPage(response.data.current_page);
    } catch (error) {
      console.error('Error fetching messages:', error);
    }
  };

  useEffect(() => {
    fetchMessages(1);
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (user && token) {
      try {
        await axios.post('/auth/add_message', { content: feedback }, {
          headers: { Authorization: `Bearer ${token}` }
        });
        setFeedback('');
        fetchMessages(1); // Refresh messages after posting
      } catch (error) {
        console.error('Error submitting feedback:', error);
      }
    } else {
      setShowLoginRegister(true);
    }
  };

  const handleAuthModalClose = (success: boolean) => {
    setShowLoginRegister(false);
    if (success) {
      // Refresh user data if needed
    }
  };

  const handlePageChange = (page: number) => {
    fetchMessages(page);
  };

  return (
    <div className="min-h-screen flex flex-col bg-gray-50">
      <Head>
        <title>留言板 - 证件魔术师</title>
        <meta name="description" content="在这里留下您的建议和反馈。" />
      </Head>

      <Header setShowLoginRegister={setShowLoginRegister} />

      <main className="flex-grow">
        <div className="max-w-4xl mx-auto px-4 py-8">
          <h1 className="text-3xl font-bold mb-6 text-gray-800">留言板</h1>
          <form onSubmit={handleSubmit} className="bg-white p-6 shadow-md rounded-lg mb-8">
            <textarea
              value={feedback}
              onChange={(e) => setFeedback(e.target.value)}
              placeholder="请在这里留下您的建议..."
              className="w-full p-3 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              rows={4}
              required
            />
            <button type="submit" className="mt-4 bg-blue-500 text-white py-2 px-6 rounded-md hover:bg-blue-600 transition duration-300 ease-in-out">
              提交留言
            </button>
          </form>

          <div className="bg-white p-6 shadow-md rounded-lg">
            <h2 className="text-2xl font-semibold mb-6 text-gray-800">留言列表</h2>
            {messages.map((message) => (
              <div key={message.id} className="mb-6 pb-6 border-b border-gray-200 last:border-b-0">
                <div className="flex items-center justify-between mb-2">
                  <p className="text-sm font-medium text-blue-600">{message.email}</p>
                  <p className="text-xs text-gray-500">{new Date(message.created_at).toLocaleString()}</p>
                </div>
                <p className="text-gray-700 whitespace-pre-wrap">{message.content}</p>
              </div>
            ))}
            <div className="flex justify-center mt-8">
              {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
                <button
                  key={page}
                  onClick={() => handlePageChange(page)}
                  className={`mx-1 px-4 py-2 rounded-md ${
                    currentPage === page 
                      ? 'bg-blue-500 text-white' 
                      : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
                  } transition duration-300 ease-in-out`}
                >
                  {page}
                </button>
              ))}
            </div>
          </div>
        </div>
      </main>

      <Footer />

      {showLoginRegister && (
        <AuthModal onClose={handleAuthModalClose} />
      )}
    </div>
  );
};

export default FeedbackPage;
